<?php
declare (strict_types = 1);

namespace app\middleware;

use app\lib\CacheKey;
use app\lib\response\JSON;
use app\model\Api;
use app\model\User;
use think\facade\Cache;
use think\facade\Config;

class ApiAuth
{
    /**
     * Api权限验证中间件
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //查询用户信息
        $user = User::where('id',$request->session['uid'])->with('role')->find();
        //超级管理角色直接放行
        if($user->role && $user->role->name==Config::get('admin.super_role')){
            return $next($request);
        }
        //所有已添加的api
        $allApiPaths = Cache::get(CacheKey::ALL_API_PATH);
        if(is_null($allApiPaths)){//缓存中没有从数据库中查找
            $allApiPaths = Api::where([])->column('path');
            Cache::set(CacheKey::ALL_API_PATH,$allApiPaths);
        }
        //用户有权限的api
        $roleApiPathKey = CacheKey::ROLE_API_PATH . $user->role->id;
        $roleApiPaths = Cache::get($roleApiPathKey);
        if(is_null($roleApiPaths)){//缓存中没有从数据库中查找
            $roleApiPaths = Api::whereIn('id',$user->role->api_ids)->column('path');
            Cache::set($roleApiPathKey,$roleApiPaths);
        }
        $routePath = $request->rule()->getRule();//当前接口的路由path
        $routePath = trim($routePath,'/');
        //如果访问的接口在数据库中已存在，但用户的权限中没有该接口则拦截
        if(in_array($routePath,$allApiPaths) && !in_array($routePath,$roleApiPaths)){
            return JSON::error("没有权限",JSON::CODE_NO_PERMISSION_ERROR);
        }
        return $next($request);
    }
}
